// API配置
const API_CONFIG = {
  development: '', // 开发环境使用Vite代理，所以基础URL为空
  production: 'https://huibanhao.com.cn'
}

// 获取当前环境的API基础URL
export const getApiBaseUrl = () => {
  // 优先使用环境变量中的配置
  const envApiUrl = import.meta.env.VITE_API_BASE_URL
  if (envApiUrl) {
    return envApiUrl
  }
  
  // 回退到默认配置
  const env = import.meta.env.MODE
  return API_CONFIG[env as keyof typeof API_CONFIG] || API_CONFIG.development
}

// API端点
export const API_ENDPOINTS = {
  LOGIN: '/huibanhao/login',
  LOGOUT: '/huibanhao/logout',
  USER_INFO: '/huibanhao/user'
}

// 构建完整的API URL
export const buildApiUrl = (endpoint: string) => {
  return `${getApiBaseUrl()}${endpoint}`
}

// API响应类型定义
export interface ApiResponse<T = any> {
  code: number
  msg: string
  data: T
}

export interface LoginResponse {
  token: string
  userInfo: {
    name: string
    avatar: string
    phone: string
  }
}

export interface LoginRequest {
  phone: string
  password: string
}

// HTTP客户端配置
export class ApiClient {
  private baseUrl: string

  constructor() {
    this.baseUrl = getApiBaseUrl()
  }

  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<ApiResponse<T>> {
    const url = `${this.baseUrl}${endpoint}`
    
    const defaultOptions: RequestInit = {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        ...options.headers,
      },
      credentials: 'include', // 包含cookies
      mode: 'cors', // 明确设置CORS模式
    }

    // 如果用户已登录，添加Authorization header
    const token = localStorage.getItem('auth_token')
    if (token) {
      defaultOptions.headers = {
        ...defaultOptions.headers,
        'Authorization': token,
      }
    }

    const response = await fetch(url, {
      ...defaultOptions,
      ...options,
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    return response.json()
  }

  async login(credentials: LoginRequest): Promise<ApiResponse<LoginResponse>> {
    return this.request<LoginResponse>(API_ENDPOINTS.LOGIN, {
      method: 'POST',
      body: JSON.stringify(credentials),
    })
  }

  async logout(): Promise<ApiResponse<null>> {
    return this.request<null>(API_ENDPOINTS.LOGOUT, {
      method: 'POST',
    })
  }

  async getUserInfo(): Promise<ApiResponse<LoginResponse['userInfo']>> {
    return this.request<LoginResponse['userInfo']>(API_ENDPOINTS.USER_INFO)
  }
}

// 导出默认客户端实例
export const apiClient = new ApiClient()
